package com.kvest.pendingintenttest.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.kvest.pendingintenttest.PendingIntentTestActivity;

public class MainService extends Service {
    @Override
    public void onCreate() {
        Log.d("KVEST_TAG", "create main service");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        PendingIntent pi = intent.getParcelableExtra(PendingIntentTestActivity.PENDING_INTENT_PARAMETER);
        new Thread(new Worker(pi, intent.getIntExtra(PendingIntentTestActivity.TIME_PARAMETER, 0))).start();

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d("KVEST_TAG", "destroy main service");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class Worker implements Runnable {
        private PendingIntent pi;
        private long time;

        public Worker(PendingIntent pi, long time) {
            this.pi = pi;
            this.time = time;
        }

        public void run() {
            try {
                pi.send(17);
            } catch (PendingIntent.CanceledException canceledException) {}
            try {
                Thread.sleep(time);
            } catch (InterruptedException interruptedException) {}
            try {
                Intent dataIntent = new Intent("finish action");
                pi.send(MainService.this, 18, dataIntent);
            } catch (PendingIntent.CanceledException canceledException) {}
            stopSelf();
        }
    }
}
